<template>
  <div>
    <head-top></head-top>
    <div style="margin-left:auto;margin-right:auto;margin-top:20px;display:flex;flex-direction:row;align-items:center;justify-content:center">
      <el-button type="primary" round icon="el-icon-arrow-left" :disabled="currentWeek==1" @click="subtractWeek()">上一周</el-button>
      <div class="title-date">{{startDate}} 至 {{endDate}}</div>
      <el-button type="primary" round @click="addWeek()">下一周<i class="el-icon-arrow-right el-icon--right"></i></el-button>
    </div>
    <div class="tips-container">
      <div class="tip-child-container">
        <div class="tip-border" style="background:#06c4f3"></div>空闲</div>
      <div class="tip-child-container">
        <div class="tip-border" style="background:#e94c4c"></div>占用</div>
    </div>
    <el-table v-loading="loadingArrange" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :data="testTimeArrange" border :style="'width: '+((testTeacherArrange.length+3)*120>1080?1100:(testTeacherArrange.length+3)*120)+'px;margin-left:auto;margin-right:auto;margin-top:20px;margin-bottom:100px'"
      :row-style='testRowStyle' :cell-style='testCellStyle' :cell-class-name="testCell" :span-method="testSpan" @cell-click='onCellClick'>
      <el-table-column fixed prop="date" label="日期" width="120">
      </el-table-column>
      <el-table-column fixed prop="week" label="星期" width="120">
      </el-table-column>
      <el-table-column fixed prop="time" label="时间" width="120">
      </el-table-column>
      <el-table-column v-for="(item,index) in testTeacherArrange" :prop="'teacher_'+item.teacher_id+'.student_name'" :label="item.teacher_name" width="120" v-bind:key='index'>
      </el-table-column>
    </el-table>
  
    <el-dialog v-loading="loading" title="新增排课" :visible.sync="dialogFormVisible">
      <el-row style="margin-top: 20px;">
        <el-col :span="12" :offset="4">
          <el-form :model="formData" :rules="rules" ref="formData" label-width="110px" class="demo-formData">
            <el-form-item label="选择老师">
              <el-input :placeholder="formData.teacher.username" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="选择时间" style="white-space: nowrap;">
              <el-time-select placeholder="起始时间" v-model="formData.time_from" :picker-options="{
                    							start: '07:00',
                    							step: '00:15',
                    							end: '23:45'
                    							}">
              </el-time-select>
              <el-time-select placeholder="结束时间" v-model="formData.time_to" :picker-options="{
                    							start: '07:00',
                    							step: '00:15',
                    							end: '23:45',
                    							minTime: formData.time_from,
                    							}">
              </el-time-select>
            </el-form-item>
            <el-form-item label="选择日期">
              <el-date-picker v-model="formData.date" type="date" placeholder="选择开始日期" :picker-options="pickerOptions0">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="重复次数">
              <el-input-number v-model="formData.times" :min="1" :max="99"></el-input-number>
            </el-form-item>
            <el-form-item label="选择学生">
              <el-autocomplete v-model="formData.student.username" :fetch-suggestions="querySearchAsync" placeholder="请输入学生姓名或手机号" style="width: 100%;" @select="addressSelect"></el-autocomplete>
            </el-form-item>
            <el-form-item class="button_submit">
              <el-button type="primary" @click="submitForm()">立即创建</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
  
    <el-dialog v-loading="chooseTeacherLoading" title="选择老师" :visible.sync="dialogTeacherVisible" width="30%">
      <el-tag :key="tag.teacher_name" v-for="tag in multipleSelection" closable :disable-transitions="false" @close="handleTagClose(tag)">
        {{tag.teacher_name}}
      </el-tag>
      <div style="display:flex;flex-direction:row;align-items:center;justify-content:center">
        <label>直接搜索</label>
        <el-autocomplete v-model="filterTeacher" :fetch-suggestions="queryTeacherSearchAsync" placeholder="老师姓名或手机" style="width: 250px;margin-left:10px" @select="teacherSelect"></el-autocomplete>
      </div>
      <el-table ref="multipleTable" :data="allTeacher" tooltip-effect="dark" style="width: 100%;margin-top:20px" height='500' @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="teacher_id" label="老师id" width="200">
        </el-table-column>
        <el-table-column prop="teacher_name" label="老师姓名">
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px;display:flex;flex-direction:row;align-items:center;justify-content:center">
        <el-button type="primary" @click='confirmChooseTeacher'>确认选择</el-button>
      </div>
    </el-dialog>
    <el-button type="text" @click="chooseAllTeacher" class="choose-teacher">筛选老师</el-button>
  </div>
</template>

<script>
import headTop from "@/components/headTop";
import {
  getTeacherSchedules,
  searchUser,
  getTeacherOrderedSchedules,
  addSchedule,
  getTeacherArrange,
  getAllTeacherArrange,
  getAllOrderedArrange,
  getUserInfo
} from "@/api/getData";
import moment from "moment";

export default {
  data() {
    return {
      filterTeacher: "",
      loadingArrange: false,
      allTeacher: [],
      multipleSelection: [],
      chooseTeacherLoading: false,
      dialogTeacherVisible: false,
      loading: false,
      dialogFormVisible: false,
      testTeacherArrange: [],
      testTimeArrange: [],
      testDateArrange: [],
      currentWeek: 1,
      teachers: [],
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      formData: {
        teacher_id: "",
        student_id: "",
        date: "",
        time_from: "",
        time_to: "",
        times: 1,
        student: {},
        teacher: {}
      },
      rules: {
        time: [
          {
            required: true,
            message: "请选择时间",
            trigger: "blur"
          }
        ],
        student: [
          {
            required: true,
            message: "请选择学生",
            trigger: "blur"
          }
        ]
      },
      checkTeacherSchedule: [],
      teacher_ids: [],
      startDate: "",
      endDate: ""
    };
  },
  components: {
    headTop
  },
  mounted() {
    this.getTeachers();
  },
  methods: {
    handleTagClose(tag) {
      this.$refs.multipleTable.toggleRowSelection(tag);
    },
    refreshArrange() {
      this.$bus.emit("refresh-arrange", {
        text: "123"
      });
    },
    async onCellClick(row, column, cell, event) {
      this.dialogFormVisible = true;
      this.formData.date = row.date;
      this.formData.time_from = row.time;
      this.formData.time_to = moment(this.formData.time_from, "HH:mm")
        .add(90, "m")
        .format("HH:mm");
      let propertyArr = column.property.split(".");
      let teacher_id = parseInt(propertyArr[0].split("_")[1]);
      this.formData.teacher_id = teacher_id;
      const res = await getUserInfo(teacher_id);
      if (res.resCode == 0) {
        this.formData.teacher = res.data;
      }
    },
    async chooseAllTeacher() {
      this.dialogTeacherVisible = true;
      this.chooseTeacherLoading = true;
      let reqData = {};
      reqData.teacher_ids = [];
      const res = await getAllTeacherArrange(reqData);
      this.chooseTeacherLoading = false;
      if (res.resCode == 0) {
        this.allTeacher = res.data;
      }
    },
    confirmChooseTeacher() {
      this.dialogTeacherVisible = false;
      this.teacher_ids = [];
      if (!!this.multipleSelection && this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          this.teacher_ids.push(item.teacher_id);
        });
      }
      this.getTeachers();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    testRowStyle({ row, rowIndex }) {
      return "height:10px;padding:0px";
    },
    testCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 2) {
        return "height:10px;padding:0px;color:white";
      } else {
        return "height:10px;padding:0px;";
      }
    },
    testSpan({ row, column, rowIndex, columnIndex }) {
      let currentArrange = this.testTimeArrange[rowIndex];
      if (columnIndex < 2) {
        if (!!currentArrange) {
          if (currentArrange.count > 0) {
            return [currentArrange.count, 1];
          } else {
            return [0, 0];
          }
        }
      } else if (columnIndex == 2) {
        if (!!currentArrange) {
          if (currentArrange.timeCount > 0) {
            return [currentArrange.timeCount, 1];
          } else {
            return [0, 0];
          }
        }
      } else {
        let keyArr = column.property.split(".");
        let teacherKey = keyArr[0];
        if (!!currentArrange) {
          let currentTime = currentArrange[teacherKey];
          if (!!currentTime) {
            if (currentTime.count > 0) {
              return [currentTime.count, 1];
            } else if (currentTime.count == 0) {
              return [0, 0];
            }
          }
        }
      }
    },
    testCell({ row, column, rowIndex, columnIndex }) {
      if (columnIndex > 2) {
        let columnArr = column.property.split(".");
        if (!!row[columnArr[0]] && row[columnArr[0]][columnArr[1]] !== "") {
          return "red";
        }

        let currentTeacher = this.testTeacherArrange[columnIndex - 3];
        let week = moment(row.date).weekday();
        if (week == 0) {
          week = 7;
        }

        for (let i = 0; i < currentTeacher.schedules.length; i++) {
          let item = currentTeacher.schedules[i];
          if (week == item.day) {
            for (let j = 0; j < item.time_spans.length; j++) {
              let arrange = item.time_spans[j];
              if (row.time >= arrange.time_from && row.time < arrange.time_to) {
                return "blue";
              }
            }
            break;
          }
        }
      }
    },
    changeDay2Week(day) {
      switch (day) {
        case 1:
          return "星期一";
        case 2:
          return "星期二";
        case 3:
          return "星期三";
        case 4:
          return "星期四";
        case 5:
          return "星期五";
        case 6:
          return "星期六";
        case 0:
          return "星期日";
      }
    },
    async addWeek() {
      this.currentWeek++;
      this.initData();
    },
    async subtractWeek() {
      this.currentWeek--;
      this.initData();
    },
    async getTeachers() {
      this.loadingArrange = true;
      let teacher_request_data = {};
      teacher_request_data.teacher_ids = this.teacher_ids;
      const teacherRes = await getAllTeacherArrange(teacher_request_data);
      this.testTeacherArrange = teacherRes.data;
      this.initData();
    },
    async initData() {
      this.startDate = moment()
        .add(7 * (this.currentWeek - 1), "days")
        .format("YYYY-MM-DD");

      this.endDate = moment()
        .add(7 * this.currentWeek, "days")
        .format("YYYY-MM-DD");

      let orderedData = {};
      orderedData.teacher_ids = this.teacher_ids;
      orderedData.start_date = this.startDate;
      orderedData.end_date = this.endDate;
      const orderedRes = await getAllOrderedArrange(orderedData);
      this.testDateArrange = orderedRes.data;
      let timeArrange = [];
      for (let week = 0; week < 7; week++) {
        let addTime = moment()
          .add(7 * (this.currentWeek - 1) + week, "days")
          .format("YYYY-MM-DD");
        for (let hour = 7; hour < 24; hour++) {
          let hourTime = {};
          let week = this.changeDay2Week(moment(addTime).weekday());
          hourTime.time = (hour < 10 ? "0" : "") + hour + ":00";
          hourTime.date = addTime;
          hourTime.week = week;
          if (hour == 7) {
            hourTime.count = 68;
          }
          hourTime.timeCount = 4;
          timeArrange.push(hourTime);
          let hourTime1 = {};
          hourTime1.time = (hour < 10 ? "0" : "") + hour + ":15";
          hourTime1.date = addTime;
          hourTime1.week = week;
          timeArrange.push(hourTime1);
          let hourTime2 = {};
          hourTime2.time = (hour < 10 ? "0" : "") + hour + ":30";
          hourTime2.date = addTime;
          hourTime2.week = week;
          timeArrange.push(hourTime2);
          let hourTime3 = {};
          hourTime3.time = (hour < 10 ? "0" : "") + hour + ":45";
          hourTime3.date = addTime;
          hourTime3.week = week;
          timeArrange.push(hourTime3);
        }
      }
      timeArrange.forEach(item => {
        this.testDateArrange.forEach(dateItem => {
          if (item.date == dateItem.date) {
            dateItem.arrange.forEach(arrange => {
              if (
                item.time >= arrange.time_from &&
                item.time < arrange.time_to
              ) {
                let teacherIdKey = "teacher_" + arrange.teacher_id;
                let arrangeData = {
                  teacher_id: arrange.teacher_id,
                  teacher_name: arrange.teacher_name,
                  student_id: arrange.student_id,
                  student_name: arrange.student_name
                };
                item[teacherIdKey] = arrangeData;
              }
            });
          }
        });
      });
      this.testTeacherArrange.forEach(item => {
        let teacherId = "teacher_" + item.teacher_id;
        let count = "count";
        let sum = 0;

        for (let index = 0; index < timeArrange.length; index++) {
          let timeItem = timeArrange[index];
          if (teacherId in timeItem) {
            sum++;
            timeItem[teacherId][count] = 0;
          }
          if (
            (index >= timeArrange.length - 1 ||
              !(teacherId in timeArrange[index + 1])) &&
            sum != 0
          ) {
            timeArrange[index + 1 - sum][teacherId][count] = sum;
            sum = 0;
          }
        }
      });
      this.testTimeArrange = timeArrange;
      this.loadingArrange = false;
    },
    async queryTeacherSearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const res = await searchUser(2, {
            keyword: queryString
          });
          if (res.resCode == 0) {
            res.data.forEach(item => {
              item.value = item.username;
            });
            cb(res.data);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    async querySearchAsync(queryString, cb) {
      if (queryString) {
        try {
          const res = await searchUser(3, {
            keyword: queryString
          });
          if (res.resCode == 0) {
            res.data.forEach(item => {
              item.value = item.username;
            });
            cb(res.data);
          }
        } catch (err) {
          console.log(err);
        }
      }
    },
    addressSelect(student) {
      this.formData.student = student;
      this.formData.student_id = student.id;
    },
    teacherSelect(teacher) {
      this.allTeacher.forEach(item => {
        if (item.teacher_id == teacher.id) {
          let hasSelected = false;
          this.multipleSelection.forEach(select => {
            if (select.teacher_id == item.teacher_id) {
              hasSelected = true;
            }
          });
          if (!hasSelected) {
            this.$refs.multipleTable.toggleRowSelection(item);
          }
        }
      });
    },
    async submitForm() {
      var createArrange = {};
      createArrange.teacher_id = this.formData.teacher_id;
      createArrange.student_id = this.formData.student_id;
      createArrange.date = moment(this.formData.date).format("YYYY-MM-DD");
      createArrange.time_from = this.formData.time_from + ":00";
      createArrange.time_to = this.formData.time_to + ":00";
      createArrange.times = this.formData.times;
      this.loading = true;
      const res = await addSchedule(createArrange);
      if (res.resCode == 0) {
        this.loading = false;
        this.dialogFormVisible = false;
        this.initData();
        this.$message({
          message: "创建成功",
          type: "success"
        });
        this.refreshArrange();
      } else {
        this.loading = false;
        this.$message.error(res.resMsg);
      }
    }
  }
};
</script>

<style lang="less">
@import "../style/mixin";
.el-tag + .el-tag {
  margin-left: 10px;
  margin-bottom: 10px;
}

.button_submit {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

.el-table .info-row {
  background: #c9e5f5;
}

.red {
  background: #e94c4c;
}

.green {
  background: red;
}

.blue {
  background: #06c4f3;
}

.el-table .positive-row {
  background: #e2f0e4;
}

.add_arrange {
  position: absolute;
  right: 20px;
  bottom: 100px;
  width: 60px;
  height: 60px;
  border-radius: 30px;
  background: #20a0ff;
  color: white;
  box-shadow: 0px 0px 8px #888888;
  font-size: 12px;
}

.choose-teacher {
  position: absolute;
  right: 20px;
  bottom: 20px;
  width: 60px;
  height: 60px;
  border-radius: 30px;
  background: #20a0ff;
  color: white;
  box-shadow: 0px 0px 8px #888888;
  font-size: 12px;
}

.tips-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.tip-child-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.tip-border {
  width: 10px;
  height: 10px;
  border-radius: 5px;
  margin-right: 5px;
  box-shadow: 0 0 5px #888;
}

.title-date {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #20a0ff;
  margin: 20px;
}
</style>
